import axios from "axios";
import { Base64 } from "js-base64";
import { ElMessage } from "element-plus";

// 创建 axios 实例
const http = axios.create({
  baseURL: "http://127.0.0.1:8900/apif",
  timeout: 10000,
});

// 图片上传url
export const imageUrl = "http://127.0.0.1:8900/apif/imageUpload";

// token加密
function encryptToken() {
  const adminInfor = localStorage.getItem("adminInfor");
  if (!adminInfor) return null;
  const adminInfoObj = JSON.parse(adminInfor);
  if (!adminInfoObj.user_Token) return null;
  return "Basic " + Base64.encode(adminInfoObj.user_Token + ":");
}

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = encryptToken();
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => Promise.reject(error),
);

// 响应拦截器
http.interceptors.response.use(
  (response) => response.data,
  (error) => {
    ElMessage.error(error.message || "请求失败");
    return Promise.reject(error);
  },
);

// 直接导出 http 实例
export default http;
